package com.hxh.spring.cloud.emoticon.produce.thread;

import com.alibaba.fastjson.JSONObject;
import com.hxh.spring.cloud.emoticon.produce.dto.ResultBean;
import com.hxh.spring.cloud.emoticon.produce.entity.Emoticon;
import com.hxh.spring.cloud.emoticon.produce.service.impl.EmoticonServiceImpl;
import com.hxh.spring.cloud.emoticon.produce.utils.HttpUtil;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author huangxunhui
 * Date: Created in 2019-05-10 14:17
 * Utils: Intellij Idea
 * Description:
 */
public class SaveEmoticonThread implements Runnable {

    private String url;

    private EmoticonServiceImpl emoticonService;

    public SaveEmoticonThread(String url, EmoticonServiceImpl emoticonService) {
        this.url = url;
        this.emoticonService = emoticonService;
    }

    @Override
    public void run() {
        try {
            emoticonService.saveBatch(toEmoticons(getData(url)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private List<ResultBean> getData(String url ) throws IOException {
        String responseData = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(responseData);
        Object data = jsonObject.get("data");
        return JSONObject.parseArray(data.toString(), ResultBean.class);
    }

    private List<Emoticon> toEmoticons(List<ResultBean> resultBeans){
        return resultBeans.stream().map(resultBean -> {
            Emoticon emoticon = new Emoticon();
            emoticon.setUrl(resultBean.getImageUrl());
            emoticon.setTitle(resultBean.getPackName());
            return emoticon;
        }).collect(Collectors.toList());
    }
}
